package com.sita.tboard.util;

import android.content.Context;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;

import cn.trinea.android.common.util.StringUtils;
import cn.trinea.android.common.util.ToastUtils;

/**
 * Created by xiaodong on 16/2/24.
 */
public class LocationUtils {
    public static String getCurrentAddress(){
        AMapLocation amapLocation = GlobalContext.getLocationClient().getLastKnownLocation();

        String address = amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。

        return address;
    }

    public static void getAddressForAccount(final Context context, String longitude,
                                              String latitude,
                                              final TextView textView){
        if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)){
            textView.setText(null);
            return;
        }
        final LatLonPoint latLonPoint = new LatLonPoint(Double.valueOf(latitude), Double.valueOf(longitude));
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 10,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        GeocodeSearch geocoderSearch = new GeocodeSearch(context);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                if (rCode == 0) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        String addressName = result.getRegeocodeAddress().getProvince() + " "
                                + result.getRegeocodeAddress().getCity();
                        textView.setText(addressName);
                    } else {
                        textView.setText(context.getString(R.string.no_address));
                    }
                } else if (rCode == 27) {
                    ToastUtils.show(context, R.string.network_unavailable);
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }
}
